<template>
  <div class="knowledge-container">
    <!-- 左侧 知识库选择栏 -->
    <div class="sidebar">
      <h2>知识库</h2>
      <ul>
        <li v-for="(item, index) in knowledgeList" :key="index" @click="selectKnowledge(item)">
          {{ item }}
        </li>
      </ul>
    </div>

    <!-- 右侧 聊天窗口 -->
    <div class="chat-container">
      <div class="chat-header">Neural智库</div>
      <div class="chat-box">
        <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
          <div class="message-time">{{ msg.timestamp }}</div>

          <!-- 思考内容 -->
          <div v-if="msg.think" class="thinking-content">{{ msg.think }}</div>

          <!-- 正文内容 -->
          <div v-if="msg.text" v-html="parseMarkdown(msg.text)" :class="msg.isCode ? 'code-block' : ''"></div>
        </div>

        <!-- 加载中的指示器 -->
        <div v-if="isLoading" class="loading-indicator">加载中...</div>
      </div>

      <!-- 输入框 -->
      <div class="input-container">
        <input v-model="inputMessage" type="text" placeholder="输入你的问题..." @keyup.enter="sendMessage" />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { marked } from "marked";
import "highlight.js/styles/github.css"; // 代码高亮样式

export default {
  name: "Knowledge",
  data() {
    return {
      knowledgeList: ["项目管理", "开发文档", "技术分享", "运维手册"],
      messages: [{ role: "ai", text: "你好，我是你的 AI 知识助手！"}],
      inputMessage: "",
      selectedKnowledge: "项目管理", // 默认选中的知识库
      isLoading: false, // 控制加载状态
    };
  },
  methods: {
    async sendMessage() {
      // 如果输入框为空，直接返回
      if (!this.inputMessage.trim()) return;
      const userMessage = this.inputMessage;

      // 记录用户消息并展示
      this.messages.push({ role: "user", text: userMessage, timestamp: this.formatTime() });

      // 清空输入框并设置加载状态
      this.inputMessage = "";
      this.isLoading = true;

      // 添加思考内容
      this.messages.push({ role: "ai", think: "正在思考..." , timestamp: this.formatTime()});
      try {
        const requestData = this.messages
            .filter(msg => msg.role && msg.text && msg.think !== "正在思考...") // 过滤掉没有 text 或正在思考的消息
            .slice(-10) // 只保留最后 10 条消息
            .map(msg => ({
              role: msg.role,
              text: msg.text
            }));
        console.log("发送请求数据：", JSON.stringify(requestData)); // 调试用
        const response = await axios.post("http://localhost:9090/api/AI/chat", requestData);
        let aiReply = response.data.data || "AI 没有返回内容";
        // 先移除思考消息，确保后续逻辑不会影响它
        this.messages = this.messages.filter(msg => msg.think !== "正在思考...");

        // 识别思考和正文内容
        const thinkPattern = /<think>([\s\S]+?)<\/think>/g;
        let thinkContent = "";
        let textContent = aiReply;

        // 提取思考内容
        if (thinkPattern.test(aiReply)) {
          thinkContent = aiReply.match(thinkPattern)[0].replace(/<\/?think>/g, '').trim();
          textContent = aiReply.replace(thinkPattern, '').trim();
        }
        if (thinkContent) {
          this.messages.push({ role: "ai", think: thinkContent, timestamp: this.formatTime()});
        }
        this.messages.push({ role: "ai", text: textContent, timestamp: this.formatTime()});
      } catch (error) {
        console.error("API 请求失败：", error);
        this.messages.push({ role: "ai", text: "AI 服务暂时不可用，请稍后再试。", timestamp: this.formatTime()});
      } finally {
        // 完成加载，隐藏加载状态
        this.isLoading = false;
      }
    },

    selectKnowledge(topic) {
      this.selectedKnowledge = topic;
      this.messages = [{ role: "ai", text: `已切换到【${topic}】知识库`, timestamp: this.formatTime() }];
    },

    formatTime() {
      const now = new Date();
      return now.toLocaleString(); // 格式化时间
    },

    parseMarkdown(text) {
      return marked.parse(text); // 解析 Markdown
    }
  },
};
</script>

<style scoped>
/* 整体容器 */
.knowledge-container {
  display: flex;
  height: 88vh;
  background-color: #f5f7fa;
}

/* 左侧 知识库 */
.sidebar {
  width: 260px;
  background: #ffffff;
  padding: 20px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
  border-right: 1px solid #e0e0e0;
}

.sidebar h2 {
  font-size: 18px;
  margin-bottom: 15px;
  color: #333;
}

.sidebar ul {
  list-style: none;
  padding: 0;
}

.sidebar ul li {
  padding: 10px;
  margin-bottom: 5px;
  border-radius: 8px;
  cursor: pointer;
  transition: 0.3s;
}

.sidebar ul li:hover {
  background: #e8f0fe;
}

/* 右侧 聊天框 */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 20px 30px;
  font-size: 22px;
  font-weight: bold;
  text-align: center;
  border-radius: 10px;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.message {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  margin: 5px 0;
}

.message.user {
  align-self: flex-end;
  background: #b5eb9b;
}

.message.ai {
  align-self: flex-start;
  background: #f1f1f1;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
  text-align: left;
}

/* 思考内容 */
.thinking-content {
  font-style: italic;
  color: #888;
  margin-bottom: 10px;
}

/* 代码块样式 */
pre {
  background: #282c34;
  color: #abb2bf;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
  font-size: 14px;
}

.code-block {
  font-family: "Courier New", Courier, monospace;
}

/* Markdown 内容 */
.markdown-content {
  white-space: pre-wrap;
  word-wrap: break-word;
}

/* 输入框 */
.input-container {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
  background: #f9f9f9;
}

.input-container input {
  flex: 1;
  padding: 10px;
  border-radius: 20px;
  border: 1px solid #ddd;
  outline: none;
}

.input-container button {
  background: #007bff;
  color: white;
  border: none;
  padding: 10px 15px;
  margin-left: 10px;
  border-radius: 20px;
  cursor: pointer;
}

.input-container button:hover {
  background: #0056b3;
}

/* 加载中的样式 */
.loading-indicator {
  text-align: center;
  margin-top: 20px;
  font-size: 16px;
  color: #888;
}
</style>
